package cn.cmvideo.xworld.util;

import cn.cmvideo.xworld.model.Msg;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Handler;

public class OrientationSensorListener implements SensorEventListener {
	private static final int _DATA_X = 0;
	private static final int _DATA_Y = 1;
	private static final int _DATA_Z = 2;

	public static final int ORIENTATION_UNKNOWN = -1;

	private Handler rotateHandler;

	private int oldOrientation = 0;

	public OrientationSensorListener(Handler handler) {
		rotateHandler = handler;
	}

	public void onAccuracyChanged(Sensor arg0, int arg1) {
	}

	public void onSensorChanged(SensorEvent event) {
		float[] values = event.values;
		int orientation = ORIENTATION_UNKNOWN;
		float X = -values[_DATA_X];
		float Y = -values[_DATA_Y];
		float Z = -values[_DATA_Z];
		float magnitude = X * X + Y * Y;
		// Don't trust the angle if the magnitude is small compared to the y
		// value
		if (magnitude * 4 >= Z * Z) {
			float OneEightyOverPi = 57.29577957855f;
			float angle = (float) Math.atan2(-Y, X) * OneEightyOverPi;
			orientation = 90 - (int) Math.round(angle);
			// normalize to 0 - 359 range
			while (orientation >= 360) {
				orientation -= 360;
			}
			while (orientation < 0) {
				orientation += 360;
			}

			int quadrant = 0;
			if (orientation >= 45 && orientation < 135) {
				quadrant = 1;
			} else if (orientation >= 135 && orientation < 225) {
				quadrant = 2;
			} else if (orientation >= 225 && orientation < 315) {
				quadrant = 3;
			} else if ((orientation >= 315 && orientation < 360)
					|| (orientation >= 0 && orientation < 45)) {
				quadrant = 4;
			}

			int oldQuadrant = 0;
			if (oldOrientation >= 45 && oldOrientation < 135) {
				oldQuadrant = 1;
			} else if (oldOrientation >= 135 && oldOrientation < 225) {
				oldQuadrant = 2;
			} else if (oldOrientation >= 225 && oldOrientation < 315) {
				oldQuadrant = 3;
			} else if ((oldOrientation >= 315 && oldOrientation < 360)
					|| (oldOrientation >= 0 && oldOrientation < 45)) {
				oldQuadrant = 4;
			}

			oldOrientation = orientation;

			if (quadrant != oldQuadrant && rotateHandler != null) {
				rotateHandler.obtainMessage(Msg.SENSOR_ROTATE, orientation, 0)
						.sendToTarget();
			}
		}

	}

}
